package com.fast.framework.web.plugin.redis.serializer;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * JdkSerializer
 * @author zengjintao
 * @version 1.0
 * @createTime 2017年11月3日下午3:31:52
 */
public class JdkSerializer implements ISerializer{

	/**
	 * 对象转换成bytes数组
	 */
	@Override
	public byte[] valueToBytes(Object value) {
		ObjectOutputStream objectOut = null;
		try {
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			objectOut = new ObjectOutputStream(byteOut);
			objectOut.writeObject(value);
			objectOut.flush();
			return byteOut.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			if(objectOut != null){
				try {
					objectOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public Object bytesToObject(byte[] bytes){
		if(bytes == null || bytes.length == 0)
			return null;
		
		ObjectInputStream objectIn = null;
		try {
			ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
			objectIn = new ObjectInputStream(byteIn);
			return objectIn.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			if(objectIn != null){
				try {
					objectIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
